import { createStore } from 'vuex'
import axios from 'axios'

export interface ResponseType<P = {}> {
  code: number;
  msg: string;
  data: P;
}

export interface UserProps {
  isLogin: boolean;
  nickname?: string;
  id?: number;
  columnId?: string;
  email?: string;
  avatar?: ImageProps;
}

export interface GlobalErrorProps {
  status: boolean;
  message?: string;
}

export interface GlobalDataProps {
  error: GlobalErrorProps;
  token: string;
  loading: boolean;
  columns: ColumnProps[];
  posts: PostProps[];
  user: UserProps;
}

export interface ImageProps {
  id?: string;
  url?: string;
  createdAt?: string;
  fitUrl?: string;
}

export interface ColumnProps {
  id: number;
  title: string;
  img?: Record<string, any>;
  summary: string;
  content?: string;
  avatar?: ImageProps;
  columnId?: number;
}

export interface PostProps {
  id?: string;
  title: string;
  excerpt?: string;
  content?: string;
  image?: ImageProps | string;
  createdAt?: string;
  columnId: string;
  author?: number | UserProps;
  isHTML?: boolean;
}

const store = createStore<GlobalDataProps>({
  state: {
    error: { status: false },
    token: localStorage.getItem('token') || '',
    loading: false,
    columns: [],
    posts: [],
    user: { isLogin: !!localStorage.getItem('token') , nickname: localStorage.getItem('nickname') || ''}
  },
  mutations: {
    createPost(state, newPost) {
      state.posts.push(newPost)
    },
    fetchColumns(state, rawData) {
      state.columns = rawData
    },
    fetchColumn(state, rawData) {
      state.columns = [rawData]
    },
    fetchPosts(state, rawData) {
      state.posts = rawData
    },
    fetchPost(state, rawData) {
      state.posts = rawData
    },
    fetchCurrentUser(state, rawData) {
      console.log(rawData)
      const { nickname } = rawData
      console.log(nickname)
      localStorage.setItem('nickname', nickname)
      state.user = { isLogin: true, ...rawData }
    },
    updatePost(state, { data }) {
      state.posts = state.posts.map(post => {
        if (post.id === data.id) {
          return data
        } else {
          return post
        }
      })
    },
    deletePost(state, { data }) {
      delete state.posts[data.id]
    },
    setError(state, e: GlobalErrorProps) {
      state.error = e
    },
    setLoading(state, status) {
      state.loading = status
    },
    login(state, rawData) {
      const { token } = rawData
      state.token = token
      localStorage.setItem('token', token)
      state.user = { isLogin: true }
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
    },
    logout(state) {
      state.token = ''
      state.user = { isLogin: false }
      localStorage.remove('token')
      delete axios.defaults.headers.common.Authorization
    }
  },
  actions: {
    /**
     * 获取所有专栏列表
     * @param 
     */
    async fetchColumns({ commit }) {
      const { data } = await axios.get('/api/article/lists')
      commit('fetchColumns', data)
    },
    /**
     * 专栏列表
     * @param param0 
     * @param cid 
     */
    async fetchColumn({ commit }, cid) {
      const { data } = await axios.get(`/api/article/detail/${cid}`)
      commit('fetchColumn', data)
    },
    /**
     * 获取某一专栏详情
     * @param param0 
     * @param cid 
     */
    async fetchPosts({ commit }, cid) {
      const { data } = await axios.get(`/api/article/detail/${cid}/posts`)
      commit('fetchPosts', data)
    },
    /**
     * 登录
     * @param param0 
     * @param payload 
     */
    async login({ commit }, payload) {
      const { data } = await axios.post(`/api/user/login`, payload)
      commit('login', data)
      return data
    },
    /**
     * 获取当前用户信息
     * @param param0 
     * @param payload 
     */
    async fetchCurrentUser({ commit }, payload) {
      const { data } = await axios.post('/api/user/userInfo', payload)
      commit('fetchCurrentUser', data.data)
    },
    /**
     * 获取文章详情
     * @param param0 
     * @param cid 
     */
    async fetchPost({ commit }, cid) {
      const { data } = await axios.get(`/api/article/post/${cid}`)
      commit('fetchPost', data)
      return data
    },
    /**
     * 创建文章
     * @param param0 
     * @param payload 
     */
    async createPost({ commit }, payload) {
      console.log(payload)
      const { data } = await axios.post('/api/article/create', payload)
      commit('createPost', data)
    },
    /**
     * 删除文章
     * @param param0 
     * @param id 
     */
    async deletePost({ commit }, id) {
      const { data } = await axios.delete(`/api/article/posts/${id}`)
      commit('deletePost', data)
    },
    /**
     * 登录和获取用户信息 dispatch 封装方法
     * @param param0 
     * @param loginData 
     */
    async loginAndFetch({ dispatch }, loginData) {
      return dispatch('login', loginData).then((res) => {
        console.log(res)
        return dispatch('fetchCurrentUser', loginData)
      })
    },
    /**
     * 更新文章
     * @param param0 
     * @param param1 
     */
    async updatePost({ commit }, {payload, id}) {
      const { data } = await axios.patch(`/api/posts/${id}`, payload)
      commit('updatePost', data)
    }
  },
  getters: {
    getColumnById: (state) => (id: number) => {
      return state.columns.find(c => {
        return c.id === id
      })
    },
    getPostsById: (state) => (cid: number) => {
      return state.posts.filter(post => {
        console.log(+post.columnId === +cid)
        return +post.columnId === +cid
      })
    },
    getCurrentPost: (state) => () => {
      return state.posts
    }
  }
})

export default store